<template>
  <div class="all-articles" ref="scrollContainer">
    <div class="page-header">
      <h1 v-if="!currentCategory && !currentTag">全部文章</h1>
      <h1 v-else-if="currentCategory">分类：{{ currentCategory }}</h1>
      <h1 v-else>标签：{{ currentTag }}</h1>
      
      <p v-if="!currentCategory && !currentTag">这里展示了博客的所有文章</p>
      <p v-else-if="currentCategory">探索 {{ currentCategory }} 分类下的所有文章</p>
      <p v-else>探索带有 {{ currentTag }} 标签的所有文章</p>
      
      <!-- 清除筛选按钮 -->
      <button v-if="currentCategory || currentTag" class="clear-filter" @click="clearFilter">
        查看全部文章
      </button>
    </div>
    
    <div class="articles-container">
      <!-- 文章列表将在这里显示 -->
      <div v-if="articles.length === 0 && !isLoading" class="no-articles">
        <p>暂无文章数据</p>
      </div>
      
      <div v-else class="articles-list">
        <div v-for="article in articles" :key="article._id" class="article-item">
          <h3 class="article-title">{{ article.title }}</h3>
          <div class="article-meta">
            <span class="article-date">{{ article.date }}</span>
            <span class="article-category">分类：{{ article.category.name }}</span>
          </div>
          <p class="article-excerpt">{{ article.excerpt }}</p>
          <router-link :to="`/blog/${article._id}`" class="read-more">阅读全文 →</router-link>
        </div>
        
        <!-- 加载状态 -->
        <div v-if="isLoading" class="loading-more">
          <div class="loading-spinner"></div>
          <span>加载中...</span>
        </div>
        
        <!-- 没有更多数据 -->
        <div v-if="!hasMore && articles.length > 0" class="no-more-data">
          <p>已经到底啦 ~</p>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, nextTick, watch } from 'vue'
import { useRoute } from 'vue-router'
import { useBlogStore } from '../stores/blog'

// 状态管理
const route = useRoute()
const articles = ref([])
const page = ref(1)
const pageSize = ref(5)
const isLoading = ref(false)
const hasMore = ref(true)
const scrollContainer = ref(null)
const currentCategory = ref('')
const currentTag = ref('')

// 使用 Pinia store
const blogStore = useBlogStore()

// 加载文章数据
const loadArticles = async () => {
  isLoading.value = true
  
  try {
    // 构建API请求参数
    const params = {
      page: page.value,
      pageSize: pageSize.value
    }
    
    // 如果有分类筛选，则添加分类参数
    if (currentCategory.value) {
      params.category = currentCategory.value
    }
    
    // 如果有标签筛选，则添加标签参数
    if (currentTag.value) {
      params.tag = currentTag.value
    }
    
    // 调用 store 方法获取文章数据
    const data = await blogStore.getArticles(params)
    
    if (data && data.list) {
      const newArticles = data.list
      
      // 如果是第一页，则替换数据；否则追加数据
      if (page.value === 1) {
        articles.value = newArticles
      } else {
        articles.value = [...articles.value, ...newArticles]
      }
      
      // 判断是否还有更多数据
      hasMore.value = newArticles.length >= pageSize.value
    }
  } catch (error) {
    console.error('加载文章数据失败:', error)
  } finally {
    isLoading.value = false
  }
}

// 加载更多数据
const loadMoreArticles = () => {
  if (!isLoading.value && hasMore.value) {
    page.value++
    loadArticles()
  }
}

// 清除筛选条件
const clearFilter = () => {
  currentCategory.value = ''
  currentTag.value = ''
  page.value = 1
  articles.value = []
  hasMore.value = true
  loadArticles()
}

// 滚动监听处理函数
const handleScroll = () => {
  if (!scrollContainer.value || isLoading.value || !hasMore.value) return
  
  const { scrollTop, scrollHeight, clientHeight } = scrollContainer.value
  
  // 当滚动到距离底部100px时触发加载更多
  if (scrollTop + clientHeight >= scrollHeight - 100) {
    loadMoreArticles()
  }
}

// 组件挂载时
onMounted(() => {
  // 初始化路由参数
  currentCategory.value = route.query.category || ''
  currentTag.value = route.query.tag || ''
  
  // 初始加载第一页数据
  loadArticles()
  
  // 等待DOM渲染完成后添加滚动监听
  nextTick(() => {
    if (scrollContainer.value) {
      // 使用window的scroll事件来监听滚动
      window.addEventListener('scroll', handleScroll)
    }
  })
})

// 监听路由参数变化
watch(() => route.query, (newQuery) => {
  // 当分类或标签参数变化时，重置状态并重新加载数据
  const newCategory = newQuery.category || ''
  const newTag = newQuery.tag || ''
  
  if (newCategory !== currentCategory.value || newTag !== currentTag.value) {
    currentCategory.value = newCategory
    currentTag.value = newTag
    page.value = 1
    articles.value = []
    hasMore.value = true
    loadArticles()
  }
}, { immediate: false, deep: true })

// 组件卸载时移除事件监听
onUnmounted(() => {
  window.removeEventListener('scroll', handleScroll)
})
</script>

<style scoped>
.all-articles {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

/* 清除筛选按钮样式 */
.clear-filter {
  background-color: #f0f0f0;
  border: 1px solid #d9d9d9;
  color: #333;
  padding: 6px 16px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 0.9em;
  transition: all 0.3s ease;
  margin-top: 10px;
}

.clear-filter:hover {
  background-color: #e6f7ff;
  border-color: #91d5ff;
  color: #1890ff;
}

.articles-container {
  background-color: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.no-articles {
  text-align: center;
  padding: 60px 20px;
  color: #999;
}

.articles-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.article-item {
  padding: 20px;
  border-bottom: 1px solid #f0f0f0;
  transition: all 0.3s ease;
}

.article-item:hover {
  background-color: #fafafa;
  transform: translateX(5px);
}

.article-item:last-child {
  border-bottom: none;
}

.article-title {
  font-size: 1.5em;
  margin-bottom: 10px;
  color: #262626;
}

.article-meta {
  display: flex;
  gap: 20px;
  margin-bottom: 15px;
  color: #999;
  font-size: 0.9em;
}

.article-excerpt {
  color: #666;
  line-height: 1.6;
  margin-bottom: 15px;
}

.read-more {
  color: #1890ff;
  text-decoration: none;
  font-weight: 500;
  transition: color 0.3s ease;
}

.read-more:hover {
  color: #40a9ff;
  text-decoration: underline;
}

/* 加载更多样式 */
.loading-more {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 30px;
  color: #666;
}

/* 加载动画 */
.loading-spinner {
  width: 20px;
  height: 20px;
  border: 2px solid #f3f3f3;
  border-top: 2px solid #1890ff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-right: 10px;
}

/* 旋转动画 */
@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* 没有更多数据样式 */
.no-more-data {
  text-align: center;
  padding: 30px;
  color: #999;
  font-size: 0.9em;
}

@media (max-width: 768px) {
  .all-articles {
    padding: 10px;
  }
  
  .article-title {
    font-size: 1.3em;
  }
}
</style>